﻿#include <jni.h>
#include <stdio.h>

#include "sm3_hash.h"

JNIEXPORT jint JNICALL Java_com_tianhe_common_tongsuo_SM3JNI_digest(JNIEnv *env, jobject obj,
                                          jbyteArray msg,	
                                          jbyteArray digest)
{
    if (!msg || !digest) {
        fprintf(stderr, "Java_SM3JNI_digest: invalid parameters.\n");
        return (-1);
    }

    jbyte *pucMsg = (*env)->GetByteArrayElements(env, msg, NULL);
    jsize stMsgLen = (*env)->GetArrayLength(env, msg);
    jbyte *pucDigest = (*env)->GetByteArrayElements(env, digest, NULL);
    jsize stDigestLen = (*env)->GetArrayLength(env, digest);
    if (stDigestLen < 32) {
        fprintf(stderr, "Java_SM3JNI_digest: invlid digest length %ld.\n", stDigestLen);
        return (-1);
    }

    int iResult = sm3_hash((const unsigned char *)pucMsg, stMsgLen, (unsigned char *)pucDigest);

    (*env)->ReleaseByteArrayElements(env, msg, pucMsg, JNI_ABORT);
    (*env)->ReleaseByteArrayElements(env, digest, pucDigest, 0);

    return iResult;
}